package logic

import (
	"context"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"time"
	"vipRpc/cache"
	"vipRpc/models"
	"vipRpc/pkg"

	"vipRpc/internal/svc"
	"vipRpc/vip"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateOrdersLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateOrdersLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateOrdersLogic {
	return &CreateOrdersLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateOrdersLogic) CreateOrders(in *vip.CreateOrdersRequest) (*vip.CreateOrdersResponse, error) {
	// todo: add your logic here and delete this line

	var err error
	var u models.User
	var g models.Goods
	var o models.Order
	u.ID = uint(in.UserId)
	g.ID = uint(in.GoodsId)

	if err = u.GetUserById(); err != nil {
		logx.Error("当前用户不存在")
		return nil, errors.New("当前用户不存在")
	}
	if u.Status == "封禁" {
		logx.Error("会员状态异常")
		return nil, errors.New("会员状态异常")
	}

	o.UserId = in.UserId
	o.GoodsId = in.GoodsId
	o.OrderSn = uuid.NewString()
	o.Total = 25.00
	o.PayType = in.PayType
	o.Status = in.Status

	if err = o.CreateOrder(); err != nil {
		logx.Error("订单创建失败")
		return nil, errors.New("订单创建失败")
	}

	key := fmt.Sprintf("member_%d", in.UserId)
	cache.Rdb.Set(l.ctx, key, time.Now(), time.Hour*24)

	amount := fmt.Sprintf("%.2f", o.Total)
	url := pkg.Alipay(amount, o.OrderSn)
	return &vip.CreateOrdersResponse{
		OrderSn: o.OrderSn,
		PayUrl:  url,
		Status:  in.Status,
	}, nil
}
